<script lang="ts">
  import { onMount } from 'svelte';
  import { t } from '../lib/i18n';
  import { trackEvent } from '../lib/analytics';
  import { marked } from 'marked';
  
  let changelogContent = '';
  let loading = true;
  let error = false;
  let versions = ['v1.0.0']; // 初始版本列表，后续会动态更新
  let selectedVersion = 'v1.0.0';
  
  // 使用marked默认选项
  marked.setOptions({
    gfm: true,
    breaks: true
  });
  
  /**
   * 获取可用版本列表
   */
  async function fetchVersions() {
    try {
      // 直接从服务器获取changelog目录下的所有md文件
      const response = await fetch('/api/changelog');
      
      if (!response.ok) {
        console.error(`获取版本列表失败: ${response.status}`);
        throw new Error('获取版本列表失败');
      }
      
      const files = await response.json();
      
      // 提取版本号 (vX.Y.Z.md -> vX.Y.Z)
      const availableVersions = files
        .filter((file: string) => file.endsWith('.md'))
        .map((file: string) => file.replace('.md', ''));
      
      if (availableVersions.length === 0) {
        // 如果没有找到任何版本，至少显示v1.0.0
        versions = ['v1.0.0'];
      } else {
        // 按版本号排序（降序），确保最新版本在前
        versions = availableVersions.sort((a: string, b: string) => {
          // 去掉v前缀后按语义版本号比较
          const versionA = a.replace('v', '').split('.').map(Number);
          const versionB = b.replace('v', '').split('.').map(Number);
          
          for (let i = 0; i < Math.max(versionA.length, versionB.length); i++) {
            const numA = versionA[i] || 0;
            const numB = versionB[i] || 0;
            if (numA !== numB) {
              return numB - numA; // 降序排列
            }
          }
          return 0;
        });
      }
      
      // 默认选择最新版本（列表第一个）
      if (versions.length > 0) {
        selectedVersion = versions[0];
      }
    } catch (err) {
      console.error('获取版本列表错误:', err);
      // 出错时使用默认版本
      versions = ['v1.0.0'];
      selectedVersion = 'v1.0.0';
    }
  }
  
  /**
   * 加载更新日志内容
   */
  async function loadChangelog(version: string) {
    loading = true;
    error = false;
    
    try {
      // 从静态资源目录加载，确保正确路径
      console.log(`Loading changelog for version ${version}`);
      const response = await fetch(`/changelog/${version}.md`);
      
      if (!response.ok) {
        console.error(`Failed to load changelog: ${response.status} ${response.statusText}`);
        throw new Error(`Failed to load changelog: ${response.status}`);
      }
      
      const text = await response.text();
      console.log(`Changelog content loaded, length: ${text.length} chars`);
      
      // 使用marked将markdown文本转换为HTML
      changelogContent = marked.parse(text) as string;
      
      // 跟踪事件
      trackEvent('Changelog', 'View', version);
      
    } catch (err) {
      console.error('Error loading changelog:', err);
      error = true;
    } finally {
      loading = false;
    }
  }
  
  /**
   * 版本切换处理
   */
  function handleVersionChange() {
    loadChangelog(selectedVersion);
  }
  
  onMount(async () => {
    // 获取版本列表
    await fetchVersions();
    // 加载最新版本的更新日志
    loadChangelog(selectedVersion);
  });
</script>

<div class="changelog-container">
  <div class="changelog-header">
    <h1>{$t('changelog.title')}</h1>
    <p class="subtitle">{$t('changelog.subtitle')}</p>
    
    <div class="version-selector">
      <label for="version-select">{$t('changelog.select_version')}:</label>
      <select id="version-select" bind:value={selectedVersion} on:change={handleVersionChange}>
        {#each versions as version}
          <option value={version}>{version}</option>
        {/each}
      </select>
    </div>
  </div>

  <div class="changelog-content">
    {#if loading}
      <div class="loading">
        <p>{$t('changelog.loading')}</p>
      </div>
    {:else if error}
      <div class="error">
        <p>{$t('changelog.error')}</p>
        <button on:click={() => loadChangelog(selectedVersion)}>
          {$t('common.retry')}
        </button>
      </div>
    {:else}
      <div class="markdown-content">
        {@html changelogContent}
      </div>
    {/if}
  </div>
</div>

<style>
  .changelog-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 1rem;
  }
  
  .changelog-header {
    margin-bottom: 2rem;
    text-align: center;
  }
  
  .changelog-header h1 {
    margin-bottom: 0.5rem;
    color: #2c3e50;
  }
  
  .subtitle {
    color: #666;
    margin-bottom: 1.5rem;
  }
  
  .version-selector {
    margin: 1rem 0;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
  }
  
  .version-selector select {
    padding: 0.5rem;
    border-radius: 4px;
    border: 1px solid #ccc;
    background-color: white;
    font-size: 1rem;
    min-width: 120px;
  }
  
  .changelog-content {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 2rem;
  }
  
  .loading, .error {
    text-align: center;
    padding: 2rem;
  }
  
  .error {
    color: #e53935;
  }
  
  .error button {
    margin-top: 1rem;
    padding: 0.5rem 1rem;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    border-radius: 4px;
    cursor: pointer;
  }
  
  .markdown-content {
    line-height: 1.6;
  }
  
  .markdown-content h1 {
    font-size: 2rem;
    margin: 1.5rem 0 1rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid #eee;
  }
  
  .markdown-content h2 {
    font-size: 1.5rem;
    margin: 1.5rem 0 1rem;
    color: #2c3e50;
  }
  
  .markdown-content h3 {
    font-size: 1.25rem;
    margin: 1.25rem 0 0.75rem;
    color: #34495e;
  }
  
  .markdown-content ul {
    padding-left: 1.5rem;
    margin: 1rem 0;
  }
  
  .markdown-content li {
    margin-bottom: 0.5rem;
  }
  
  .markdown-content code {
    background: #f4f4f4;
    padding: 0.2rem 0.4rem;
    border-radius: 3px;
    font-size: 0.9em;
    font-family: Consolas, Monaco, 'Andale Mono', monospace;
  }
  
  .markdown-content a {
    color: #3498db;
    text-decoration: none;
  }
  
  .markdown-content a:hover {
    text-decoration: underline;
  }
  
  @media (max-width: 768px) {
    .changelog-container {
      padding: 0.5rem;
    }
    
    .changelog-content {
      padding: 1rem;
    }
    
    .markdown-content h1 {
      font-size: 1.75rem;
    }
    
    .markdown-content h2 {
      font-size: 1.35rem;
    }
    
    .markdown-content h3 {
      font-size: 1.15rem;
    }
  }
</style> 
